package imse.team0.proc;

import imse.team0.transportation.ShipmentPriceReply;
import org.apache.camel.Exchange;
import org.codehaus.jettison.json.JSONObject;
import org.codehaus.jettison.mapped.Configuration;
import org.codehaus.jettison.mapped.MappedNamespaceConvention;
import org.codehaus.jettison.mapped.MappedXMLStreamReader;
import org.codehaus.jettison.mapped.MappedXMLStreamWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import java.io.StringWriter;
import java.io.Writer;

/**
 * @author Eugen, 5/5/12 12:23 PM
 */
public class JSONConvertor {

    private Class unmarshalClass;

    public void setUnmarshalClass(Class clazz){
       unmarshalClass = clazz;
    }

    public void marshal(Exchange ex) throws JAXBException {
        Configuration conf = new Configuration();
        MappedNamespaceConvention mnc = new MappedNamespaceConvention(conf);
        Writer writer = new StringWriter();
        XMLStreamWriter xmlStreamWriter = new MappedXMLStreamWriter(mnc, writer);
        Object obj = ex.getIn().getBody();
        JAXBContext jc = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = jc.createMarshaller();
        marshaller.marshal(obj, xmlStreamWriter);
        String json = writer.toString();
        ex.getIn().setBody(json);
        ex.getIn().setHeader("unmarshalClass", obj.getClass());
    }

    public void unmarshal(Exchange ex) throws Exception {
        Class clazz = ex.getIn().getHeader("unmarshalClass", Class.class);
        JAXBContext jc = JAXBContext.newInstance(ShipmentPriceReply.class);
        String body = ex.getIn().getBody(String.class);
        JSONObject obj = new JSONObject(body);
        Configuration config = new Configuration();
        MappedNamespaceConvention con = new MappedNamespaceConvention(config);
        XMLStreamReader xmlStreamReader = new MappedXMLStreamReader(obj, con);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Object reply = unmarshaller.unmarshal(xmlStreamReader);
        ex.getIn().setBody(reply);
    }
}
